﻿using System;
using System.Collections.Generic;
using System.Linq;
using Common.Logging;
using TSharp.Core.Osgi;
[assembly: RegExtensionPoint(typeof(ApplicationCleanManager))]
namespace TSharp.Core.Osgi
{
    internal class ApplicationCleanManager : ExtensionPoint<RegAppEndAttribute>
    {
        private static ILog log = LogManager.GetLogger<ApplicationCleanManager>();
        public static readonly List<RegAppEndAttribute> DisposableList = new List<RegAppEndAttribute>();

        public static void Clean(OsgiEngine engine)
        {
            lock (DisposableList)
            {


                if (!_isCleaned)
                {
                    var disables = DisposableList.Select(x => x.New());

                    disables.Foreach(v =>
                                        {
                                            try
                                            {
                                                v.Clean(engine);
                                            }
                                            catch (Exception ex)
                                            {
                                                log.ErrorFormat("{0},执行Clean时出错。", v, ex);
                                            }
                                        });
                    _isCleaned = !_isCleaned;
                }
            }
        }
        private static bool _isCleaned = false;
        protected override void Register(System.Reflection.Assembly assembly, RegAppEndAttribute attribute)
        {
            DisposableList.Add(attribute);
        }
        private static Type cleanType = typeof(IOsgiDispose);

        protected override void UnRegister(System.Reflection.Assembly assembly, RegAppEndAttribute attribute)
        {
            DisposableList.Remove(attribute);
        }
    }
}